const router = require('koa-router')()
const mongoose = require('mongoose')
const bcrypt = require(`bcryptjs`)
const statsfn = require('../lib/statsfn')

const Image = mongoose.model('Image')
const Comment = mongoose.model('Comment')
const User = mongoose.model('User')

router.get('/', async (ctx, next) => {
  if(JSON.stringify(ctx.session) == "{}") {
    const images = await Image.find({})
    .sort({createdAt: -1}).limit(20)
    const comments = await Comment.find({})
    .sort({createdAt: -1}).limit(3)
    const stats = await statsfn()
    await ctx.render('index_nosession', {
      title: '图片共享', images, comments, stats, user: undefined
    })
  } else {
    const images = await Image.find({})
      .sort({createdAt: -1}).limit(20)
      const comments = await Comment.find({})
    .sort({createdAt: -1}).limit(3)
    const stats = await statsfn()
    await ctx.render('index', {
      title: '图片共享', images, comments, stats, user: ctx.session.user
    })
  }
})

router.get('/login', async ctx => {
  await ctx.render('login')
})

router.post('/login', async ctx => {
  const {username, password} = ctx.request.body
  const user = await User.find({username:`${username}`})
  if(!user)
    ctx.redirect(`/`)
  else if(bcrypt.compareSync(password, user[0].password)) {
    ctx.session.user = {nickname: user[0].nickname, username: user[0].username}
    ctx.redirect('/')
  }
})
  
router.get('/register', async ctx => {
  await ctx.render('register')
})

router.post('/register', async ctx => {
  let {username, nickname, password} = ctx.request.body
  const salt = bcrypt.genSaltSync(10);
  password = bcrypt.hashSync(password, salt)
  await User.create({
    username, nickname, password
  })
  ctx.session.user = {nickname: nickname, username: username}
  ctx.redirect('/')
})

router.get('/logout', async ctx => {
  ctx.session.user = undefined
  ctx.redirect('/')
})

module.exports = router